#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: henry_oulen@163.com
@file: factory.py
@time: 2023/10/26 16:23
@desc: 
"""
import time

from tornado import gen

from backend.tvadmin.system.models.factory import Factory
from backend.tvadmin.utils.base_requeset import BaseHttpHandler
from backend.tvadmin.utils.mysql_base import MysqlSqlalchemy


class FactoryView(BaseHttpHandler):

    # def __int__(self):
    #     super.__init__()

    @gen.coroutine
    def get(self, *args, **kwargs):
        return_dict = yield self.get_all_sql()
        # session = MysqlSqlalchemy().session
        # result = session.query(FactoryModel).filter().all()
        # print(result)
        # for i in result:
        #     print(i.id)
        # return_data = [{"id": i.id, "factory_name": i.factory_name} for i in result]
        # return_dict = {"code": 200,
        #                "data": return_data,
        #                "status": "success"}
        print(return_dict)
        return self.write(return_dict)
        # self.write_response(ips[2], rep_dict['rep3'])

    def post(self, *args, **kwargs):
        # FactoryView
        # session = MysqlSqlalchemy().session
        # NewUser = FactoryModel(factory_name="pyt2hon", license_id="1234562789101", factory_id="C2hina1", phone="b2a1ba",
        #                        is_delete=0)
        # session.add(NewUser)
        # session.commit()  # 需要调用commit()方法提交事务。
        NewUser = Factory(factory_name=str(int(time.time())), license_id=str(int(time.time())),
                               factory_id=str(int(time.time())), phone=str(int(time.time())),
                               is_delete=0)
        Factory.add(NewUser)
        # self.db.add(NewUser)
        # self.db.commit()

    def put(self, *args, **kwargs):
        user_id = 1
        session = MysqlSqlalchemy().session
        query_user = session.query(Factory).filter_by(id=user_id).first()
        # 更新用户id为1的数据
        query_user.factory_name = "赵六"
        # query_user.age = 25
        # 提交修改
        session.commit()

    def delete(self, *args, **kwargs):
        user_id = 1
        session = MysqlSqlalchemy().session
        query_user = session.query(Factory).filter_by(id=user_id).first()
        # 更新用户id为1的数据
        query_user.factory_name = "赵222六"
        session.commit()

    # @staticmethod
    @gen.coroutine
    def get_all_sql(self):
        # session = MysqlSqlalchemy().session
        # result = self.mysql_session.query(FactoryModel).filter().all()
        result = self.db.query(Factory).filter().all()
        print(result)
        for i in result:
            print(i.id)
        return_data = [{"id": i.id, "factory_name": i.factory_name} for i in result]
        return_dict = {"code": 200,
                       "data": return_data,
                       "status": "success"}
        raise gen.Return(return_dict)
